package spring.chatroom.java_chatroom.common.utils;

import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MailUtil {

    @Value("${spring.mail.username}")
    private String from;

    //会爆有可能时因为第三方的库红线 但是没有影响 忽略就是
    @Autowired
    private JavaMailSender mailSender;

    public String sendSampleMail(String to, String tile, String context) {
        if(!RegexUtil.checkMail(to)){
            return "邮箱的格式错误";
        }

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(tile);
        message.setText(context);

        try {
            mailSender.send(message);
        } catch (Exception e) {
            log.error("向{}发送邮件失败！", to, e);
            return e.getMessage();
        }
        return null;
    }

    public String sendHtmlMail(String to, String subject, String htmlContent) {
        if(!RegexUtil.checkMail(to)){
            return "邮箱的格式错误";
        }

        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); // 关键：设置为true
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(htmlContent, true);

            mailSender.send(message);

        } catch (Exception e) {
            log.error("向{}发送邮件失败！", to, e);
            return e.getMessage();

        }
        return null;
    }

}
